package j20251112;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class Demo7 {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(3);

        // 创建多个 Callable 任务
        List<Callable<String>> tasks = new ArrayList<>();
        for (int i = 1; i <= 5; i++) {
            final int taskId = i;
            tasks.add(() -> {
                System.out.println("执行任务 " + taskId + " 在线程: " +
                        Thread.currentThread().getName());
                Thread.sleep(1000);
                return "任务 " + taskId + " 完成";
            });
        }

        try {
            // 提交所有任务并获取 Future 列表
            List<Future<String>> futures = executor.invokeAll(tasks);

            // 获取所有任务结果
            for (Future<String> future : futures) {
                try {
                    String result = future.get();
                    System.out.println("结果: " + result);
                } catch (ExecutionException e) {
                    System.out.println("任务执行异常: " + e.getMessage());
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
        }
    }
}
